package com.example.himalaya.view.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Rect;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.himalaya.R;

import com.example.himalaya.view.adapters.TrackListAdapter;
import com.example.himalaya.base.BaseApplication;
import com.example.himalaya.view.callback.IDownloadedMusicViewCallback;
import com.example.himalaya.presenters.DownloadedMusicPresenter;
import com.example.himalaya.presenters.PlayerPresenter;
import com.example.himalaya.view_component.UILoader;
import com.ximalaya.ting.android.opensdk.model.track.Track;

import net.lucode.hackware.magicindicator.buildins.UIUtil;

import java.util.List;
import java.util.Objects;

public class DownloadedMusicActivity extends AppCompatActivity {

    private UILoader mUiLoader;
    private FrameLayout mSuccessView;
    private RecyclerView mLoveSongList;
    private TrackListAdapter mTrackListAdapter;
    private DownloadedMusicPresenter mDownloadedMusicPresenter;
    private FrameLayout mMusicContainer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_downloaded_music);

        //检查应用是否已经获得授权
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            //如果没有授权就动态申请授权
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
        }

        initVariable();

        initPresenter();

        initUiLoader();

        initCallback();

        initData();

        initView();
    }

    private void initVariable() {
        mMusicContainer = this.findViewById(R.id.downloaded_music_container);
    }

    private void initView() {
        mMusicContainer.addView(mUiLoader);
    }

    private void initCallback() {
        mDownloadedMusicPresenter.registerViewCallback(new IDownloadedMusicViewCallback() {
            @Override
            public void onMusicLoaded(List<Track> tracks) {

                if (tracks != null) {
                    if (tracks.size() == 0) {
                        mUiLoader.updateStatus(UILoader.UIStatus.EMPTY);
                    } else {
                        mUiLoader.updateStatus(UILoader.UIStatus.SUCCESS);

                        mTrackListAdapter.setData(tracks);
                    }
                } else {
                    mUiLoader.updateStatus(UILoader.UIStatus.ERROR);
                }

            }

            @Override
            public void onMusicDeleted(boolean isOk) {

            }

            @Override
            public void onMusicSearched(List<Track> tracks) {

            }
        });
    }

    private void initPresenter() {
        mDownloadedMusicPresenter = DownloadedMusicPresenter.getDownloadedMusicPresenter();
    }

    private void initData() {
        mDownloadedMusicPresenter.getMusic();

        mUiLoader.updateStatus(UILoader.UIStatus.LOADING);
    }

    private void initUiLoader() {

        mUiLoader = new UILoader(BaseApplication.getAppContext()) {
            @Override
            protected View getSuccessView(ViewGroup container) {
                return createSuccessView(container);
            }
        };
    }

    private View createSuccessView(ViewGroup container) {
        mSuccessView = (FrameLayout) LayoutInflater.from(BaseApplication.getAppContext()).inflate(R.layout.song_list, container, false);

        initSuccessVariable();

        initSuccessPresenter();

        initSuccessAdapter();

        initSuccessListener();

        initSuccessView();

        return mSuccessView;
    }

    private void initSuccessListener() {
        mTrackListAdapter.setItemClickListener(new TrackListAdapter.ItemClickListener() {
            @Override
            public void onItemClick(List<Track> detailData, int position) {
                // 设置播放器的数据
                PlayerPresenter playerPresenter = PlayerPresenter.getPlayerPresenter();

                playerPresenter.setPlayList(detailData, position);

                // 跳转到播放器界面
                Intent intent = new Intent(Objects.requireNonNull(BaseApplication.getAppContext()), PlayerViewActivity.class);

                startActivity(intent);
            }
        });
        mTrackListAdapter.setItemLongClickListener(new TrackListAdapter.ItemLongClickListener() {
            @Override
            public void onItemLongClick(Track track) {

            }
        });
    }

    private void initSuccessVariable() {
        mLoveSongList = mSuccessView.findViewById(R.id.song_list);
    }

    private void initSuccessPresenter() {

    }


    private void initSuccessAdapter() {
        mTrackListAdapter = new TrackListAdapter();

        mLoveSongList.setAdapter(mTrackListAdapter);
    }

    private void initSuccessView() {
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(BaseApplication.getAppContext());
        mLoveSongList.setLayoutManager(layoutManager);

        mLoveSongList.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                outRect.top = UIUtil.dip2px(view.getContext(), 5);
                outRect.bottom = UIUtil.dip2px(view.getContext(), 5);
                outRect.left = UIUtil.dip2px(view.getContext(), 5);
                outRect.right = UIUtil.dip2px(view.getContext(), 5);
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == 1) {
            if (!(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
                Toast.makeText(this, "为获取文件读取权限", Toast.LENGTH_LONG).show();
                finish();
            }
        }
    }
}
